package com.hippo.core.util;

import com.aliyun.credentials.utils.StringUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

/**
 * 钉机器人工具类
 *
 * @author hippo
 */
@Slf4j
public class DingTalkUtils {
    /**
     * 钉钉群设置 webhook, 支持重置
     */
    private static String ACCESS_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=";

    private static String SECRET = "";

    public DingTalkUtils(String ACCESS_TOKEN1, String SECRET) {
        try {
            DingTalkUtils.SECRET = SECRET;
            DingTalkUtils.ACCESS_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=";
            DingTalkUtils.ACCESS_TOKEN = ACCESS_TOKEN + ACCESS_TOKEN1;
            client = new DefaultDingTalkClient(DingTalkUtils.ACCESS_TOKEN + sign());
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息类型
     */
    private static final String MSG_TYPE_TEXT = "text";

    /**
     * 客户端实例
     */
    public static DingTalkClient client;

//    static {
//        try {
//            client = new DefaultDingTalkClient(ACCESS_TOKEN + sign());
//        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 发送普通文本消息
     *
     * @param content    文本消息
     * @param mobileList 指定@ 联系人
     * @param isAtAll    是否@ 全部联系人
     * @return OapiRobotSendResponse
     */
    public  OapiRobotSendResponse sendMessageByText(String content, List<String> mobileList, boolean isAtAll) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        //参数	参数类型	必须	说明
        //msgtype	String	是	消息类型，此时固定为：text
        //content	String	是	消息内容
        //atMobiles	Array	否	被@人的手机号(在content里添加@人的手机号)
        //isAtAll	bool	否	@所有人时：true，否则为：false
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        if (!CollectionUtils.isEmpty(mobileList)) {
            // 发送消息并@ 以下手机号联系人
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setAtMobiles(mobileList);
            at.setIsAtAll(isAtAll);
            request.setAt(at);
        }
        request.setMsgtype(DingTalkUtils.MSG_TYPE_TEXT);
        request.setText(text);
        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = DingTalkUtils.client.execute(request);
        } catch (ApiException e) {
            log.error("[发送普通文本消息]: 发送消息失败, 异常捕获{}", e.getMessage());
        }
        return response;
    }

    /**
     * 获取签名
     * 把timestamp+"\n"+密钥当做签名字符串，使用HmacSHA256算法计算签名，然后进行Base64 encode，最后再把签名参数再进行urlEncode，得到最终的签名（需要使用UTF-8字符集）。
     * timestamp 当前时间戳，单位是毫秒，与请求调用时间误差不能超过1小时。
     * secret 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串。
     *
     * @return java.lang.String
     */
    private static String sign() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + SECRET;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(SECRET.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        return "&timestamp=" + timestamp + "&sign=" + sign;
    }

    public static void main(String args[]) {
        //发送普通文本消息
        DingTalkUtils dingTalkUtils = new DingTalkUtils("", "");
        String notice =
                "> 执行计划：【%s】 \n" +
                        "> 执行人员：%s \n" +
                        "> 开始时间：%s \n" +
                        "> 结束时间：%s \n" +
                        "> 执行耗时：%s秒 \n" +
                        "> 成功步骤：%s \n" +
                        "> 失败步骤：%s \n" +
                        "> 跳过步骤：%s \n" +
                        "> 执行计划已执行完成，请及时查看。";
        notice = String.format(notice, "短信模板场景", "柯南", "2023-05-06 15:17:39", "2023-05-06 15:17:43", "10", "30", "1", "11");
        dingTalkUtils.sendMessageByText(notice, Arrays.asList(""), false);

    }
}

